<?php

class Agitum_Controller_Plugin_IdentityLoader extends Zend_Controller_Plugin_Abstract
{
    private $user;
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
//        printf( "Class: %s; Method: %s, File: %s; Line: %s<br/>\n", __CLASS__, __FUNCTION__, __FILE__, __LINE__);

		$auth = Zend_Auth::getInstance();
		if ( $auth->hasIdentity() ) {
			$this->user = $auth->getIdentity();
		} else {
		    $user_id = Agitum_Model_User::GUEST_USER_ID;
			$slot = new Agitum_Model_Cache_Slot_User($user_id);
			$this->user = $slot->load();
			if ( !$this->user ) {
				$this->user = new Agitum_Model_User();
				$this->user->id = $user_id;
				$this->user->find();
				$slot->addTag(new Agitum_Model_Cache_Tag_User($user_id));
				$slot->save($this->user);
			}
			$auth->authenticate($this->user);
		}

		Zend_Registry::set('Logged_User', $this->user);
	}
}